
'use strict';

const glob = require('glob');
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin =  require('friendly-errors-webpack-plugin');

// 多页页面应用
const setMAP = () => {
	const entry = {};
	const HtmlWebpackPlugins = [];
	const entryFiles = glob.sync(path.join(__dirname, './src/*/*.js'));

	Object.keys(entryFiles).map((index) => {
		const entryFile = entryFiles[index];

		const match = entryFile.match(/src\/(.*)\/index\.js/);
		const pageName = match && match[1];
		entry[pageName] = entryFile;

		HtmlWebpackPlugins.push(
			new HtmlWebpackPlugin({
				title:'search',
				template: path.resolve(__dirname, `src/${pageName}/index.template.html`),
				hash: false,
				filename: `${pageName}.html`,
				inject: true,
				chunks: [pageName],
				minify: {
					html5:true,
					collapseWhitespace: true,
					preserveLineBreaks:true,
					minifyCSS:true,
					minifyJS:true,
					removeComments: true,
					removeAttributeQuotes: true
				}
			})
		)
	});


	return {
		entry,
		HtmlWebpackPlugins
	}
};

const {entry,HtmlWebpackPlugins } = setMAP();



module.exports = {
	entry: entry,
	output: {
		path: path.join(__dirname, 'dist'),
		filename: "[name].js"
	},
	mode: "development",
	devtool: "source-map",
	module: {
		rules: [
			{
				test: /.js$/,
				use: 'babel-loader'
			},
			{
				test: /.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /.less$/,
				use: ['style-loader', 'css-loader', 'less-loader']
			},
			{
				test: /\.(png|svg|kpg|gif|jpeg|jpg)$/,
				use: [{
					loader: "url-loader",
					options: {
						limit:10240
					}
				}]
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['file-loader']
			}
		]
	},
	plugins: [
		new webpack.HotModuleReplacementPlugin(),
		new CleanWebpackPlugin(),
		new FriendlyErrorsWebpackPlugin(),
	].concat(HtmlWebpackPlugins),

	devServer: {
		contentBase:'./dist',
		hot:true,
		stats: "errors-only"
	}
};
